import 'package:dio/dio.dart';
import 'package:lai_zhan/common/util/LocalStorage.dart';
import 'package:connectivity/connectivity.dart';
import 'ResultData.dart';
import 'Code.dart';
import 'package:lai_zhan/common/config/Config.dart';
import 'dart:convert';
import 'dart:io';
import 'package:cookie_jar/cookie_jar.dart';
import 'package:path_provider/path_provider.dart';

class HttpManager {


  /**
   * path 路由
   * params 参数
   * header 请求头
   * options 请求配置
   */
  static netPost(path, params, [Map<String, String> header]) async {
    //检测网络
    print(path);
    print(params);
    var connectivityResult = await (new Connectivity().checkConnectivity());
    if(connectivityResult == ConnectivityResult.none) {
      return new ResultData("", false, Code.NETWORK_ERROR);
    }
    print('网络完好');
    Map<String,String> headers = new Map();
    headers["contentType"] = "application/json";
    headers["charset"] = "UTF-8";
    if(header !=null){
      headers.addAll(header);
    }
    Options options = new Options(baseUrl: Config.baseUrl,headers: headers,connectTimeout: 1000);
    Dio dio= new Dio(options);
    Directory tempDir = await getTemporaryDirectory();
    String tempPath = tempDir.path;
    dio.cookieJar = new PersistCookieJar(tempPath);
    Response response;
    try{
      response = await dio.post(path,data: json.encode(params));
    }on DioError catch(e) {
      Response errorResponse;
      if(e.response !=null) {
        errorResponse = e.response;
      }else {
        errorResponse = new Response(statusCode: -10);
      }
      if(e.type == DioErrorType.CONNECT_TIMEOUT) {
        errorResponse.statusCode = Code.NETWORK_TIMEOUT;
      }
      if(Config.DEBUG) {
        print('请求异常: ' + e.toString());
        print('请求异常url: ' + path);
      }
      return new ResultData(null, false, errorResponse.statusCode);
    }
    print(response.data);
    return new ResultData(response.data, true, Code.SUCCESS);
  }
}
